// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const { type } = event
  const { OPENID } = cloud.getWXContext()

  try {
    let query = {}

    switch (type) {
      case 'owner':
        // 获取业主的申请记录
        const { data: users } = await db.collection('users')
          .where({
            _openid: OPENID
          })
          .get()

        if (users.length === 0) {
          return {
            success: false,
            message: '用户不存在'
          }
        }

        query = {
          applicantId: users[0]._id
        }
        break

      case 'admin':
        // 管理员查看所有待审批的申请
        query = {
          status: 'pending'
        }
        break

      case 'security':
        // 保安查看所有已批准的申请
        query = {
          status: 'approved',
          // 只显示24小时内的申请
          entryTime: _.gte(new Date(Date.now() - 24 * 60 * 60 * 1000))
        }
        break

      default:
        return {
          success: false,
          message: '无效的查询类型'
        }
    }

    // 查询申请记录
    const { data } = await db.collection('applications')
      .where(query)
      .orderBy('createTime', 'desc')
      .get()

    return {
      success: true,
      data
    }

  } catch (error) {
    console.error(error)
    return {
      success: false,
      message: '获取申请记录失败'
    }
  }
} 